/*********************************** Javascript general functions ****************************************/

function addRemoveSlug(control, fieldSlug)
{
  var fieldSlug = $(fieldSlug);
  var checking = true;
  if (control.checked)
  {
  	var slug = "[" + control.value + "]";
    fieldSlug.value = fieldSlug.value + slug;
    checking = true;
  }
  else
  {
    fieldSlug.value = fieldSlug.value.replace("[" + control.value + "]", "");
    checking = false;
  }
  
  control = $(control);
  var ancestors = control.ancestors();
  
  for (a in ancestors)
  {
  	if (ancestors[a].tagName == "TR")
  	{
  	  if (checking)
  	  {
  		ancestors[a].addClassName("selected");
  	  }
  	  else
  	  {
  		ancestors[a].removeClassName("selected");
  	  }
  		
  	  break;
  	}
  }
}
/**** category ****/
function addRemoveSlugCategory(control, module, id)
{
  var fieldSlug  = $(module+'_slug');
  var fieldName     = $(module+'_name');
  var fieldId       = $(module+'_id');
  var div           = $('div_'+module+'_selected');
  
  var checking = true;
  if (control.checked)
  {
  	var slug = "[" + control.value + "]";
    fieldSlug.value = fieldSlug.value + slug;
	
	fieldId.value   = id;
    checking = true;
	fieldName.value = control.name;
	div.innerHTML   = fieldName.value;
  }
  else
  {
	//hideBlock
	if ($('categories_move_goto').style.display!='none')
      hideBlock('categories_move_goto');
	  
    fieldSlug.value = fieldSlug.value.replace("[" + control.value + "]", "");
    checking = false;
  }
  
  control = $(control);
  var ancestors = control.ancestors();
  
  for (a in ancestors)
  {
  	if (ancestors[a].tagName == "TR")
  	{
  	  if (checking)
  	  {
  		ancestors[a].addClassName("selected");
  	  }
  	  else
  	  {
  		ancestors[a].removeClassName("selected");
  	  }
  		
  	  break;
  	}
  }
}

function getUrl(url)
{
  /*for (var i=1; i<arguments.length; i++)
  {
	alert(arguments[i]);
  }*/	
  for (var i=1; i<arguments.length; i++)
  {
    var varval = arguments[i].split("=");
    if (varval.length == "2")
    {
      if (varval[0] != "order")
      {
        url = url.replace(varval[0], varval[1]);
      }
      else
      {
	    var field = varval[0] + "\/max";
	    var re = new RegExp(field);
	    url = url.replace(re, varval[1] + "/max");
      }
    	
      continue;
    }
    
    if (varval[0] == "from" || varval[0] == "to")
    {
      var date = validateFromTo(varval[0]);
      if (date)
      {
        url = url.replace(varval[0], date);
        continue;
      }
      else
      {
        return;
      }
    }
    //*** POCH 2009-03-04 ***//
    if (varval[0] == "md_from" || varval[0] == "md_to")
    {
      var date = validateMonthDayFromTo(varval[0]);
      if (date)
      {
        url = url.replace(varval[0], date);
        continue;
      }
      else
      {
        return;
      }
    }
    //***  ***//
    if (varval[0] == "date")
    {
      var date = validateDate();
      if (date)
      {
        url = url.replace(varval[0], date);
        continue;
      }
      else
      {
        return;
      }
    }
    
    
    var value = $(varval[1]).value;

    if (varval[0] == "slug")
    {
      value = value.substr(1, value.length - 2);
      value = value.replace(/\]\[/g, ",");
    }

    
    if (varval[3] == "v")
    {
      var values = value.split(",");
      
      if (value.length == 0)
      {
      	alert("You must select a record to perform this action");
      	return;
      }
      
      if (values.length > 1 && varval[4] == "e")
      {
      	alert("You can select just one record to perform this action");
      	return;
      }
      if (varval[4] == "d")
      {
      	if (!confirm('Do you really want to delete this record(s)?'))
      	{
      	  return;
      	}
      }
      if (varval[4] == "sp")
      {
      	if (!confirm('Do you really want to Send his/her Password?'))
      	{
      	  return;
      	}
      }
    }
    
    if (varval.length >= 3)
    {
      value = value != "" ? value : "0";
      
      if (varval[3] == "u")
      {
        value = getUrlFromName(value);
      }
      
      /*
      if (varval[0] != "order")
      {
        url = url.replace(varval[0], value);
      }
      else
      {
        var field = varval[0] + "\/max";
        var re = new RegExp(field);
        url = url.replace(re, value + "/max");
      }
      */
      
      if (varval[0] == "page")
      {
        var field = "(.+" + varval[0] + ".+)\/page";
        var re = new RegExp(field);
        url = (myArray = re.exec(url)) ? myArray[1] + "/" + value : url.replace(varval[0], value);
      }
      else if (varval[0] == "order")
      {
        var field = varval[0] + "\/max";
        var re = new RegExp(field);
        url = url.replace(re, value + "/max");
      }
      else if (varval[0] == "max")
      {
        var field = varval[0] + "\/page";
        var re = new RegExp(field);
        url = url.replace(re, value + "/page");
      }
      else
      {
        url = url.replace(varval[0], value);
      }
    }
  }
  document.location.href = url;
}

function validateFromTo(param)
{
  var from = Array();
  var to   = Array();
  
  var from_year  = $("from_year").value;
  var from_month = $("from_month").value;
  var from_day   = $("from_day").value;
  var to_year    = $("to_year").value;
  var to_month   = $("to_month").value;
  var to_day     = $("to_day").value;
      	
  if (from_year == "" && from_month == "" && from_day == "")
  {
    from[1] = "0";
  }
  else if (from_year != "" && from_month != "" && from_day != "")
  {
    from[0] = from_year  + "-" + from_month + "-" + from_day;
    from[1] = from_month + "-" + from_day   + "-" + from_year;
  }
  else
  {
    alert("You must choose a correct date in the 'From' field");
    return false;
  }
      	
  if (to_year == "" && to_month == "" && to_day == "")
  {
    to[1] = "0";
  }
  else if (to_year != "" && to_month != "" && to_day != "")
  {
    to[0] = to_year  + "-" + to_month + "-" + to_day;
    to[1] = to_month + "-" + to_day   + "-" + to_year;
  }
  else
  {
    alert("You must choose a correct date in the 'To' field");
    return false;
  }

  if (from[1] == "0" || to[1] == "0")
  {
    return param == "from" ? from[1] : to[1];
  }
      	
  if (Validation.dateRange(from[0], to[0]))
  {
    return param == "from" ? from[1] : to[1];
  }
  else
  {
    alert("The date in the 'From' field must be less than the date in the 'To' field");
    return false;
  }
}
//*** POCH 2009-03-04 ***//
function validateMonthDayFromTo(param)
{
  var from = Array();
  var to   = Array();
  
  var from_month = $("md_from_month").value;
  var from_day   = $("md_from_day").value;
  var to_month   = $("md_to_month").value;
  var to_day     = $("md_to_day").value;
  
  if (from_month == "" && from_day == "")
  {
    from[1] = "0";
  }
  else if (from_month != "" && from_day != "")
  {
    from[0] = from_month + "-" + from_day;
    from[1] = from_month + "-" + from_day;
  }
  else
  {
    alert("You must choose a correct date in the 'From' field");
    return false;
  }
      	
  if (to_month == "" && to_day == "")
  {
    to[1] = "0";
  }
  else if (to_month != "" && to_day != "")
  {
    to[0] = to_month + "-" + to_day;
    to[1] = to_month + "-" + to_day;
  }
  else
  {
    alert("You must choose a correct date in the 'To' field");
    return false;
  }
  
  if (from[1] == "0" || to[1] == "0")
  {
    return param == "md_from" ? from[1] : to[1];
  }
      	
  if (Validation.MonthDayRange(from[0], to[0]))
  {
    return param == "md_from" ? from[1] : to[1];
  }
  else
  {
    alert("The date in the 'From' field must be less than the date in the 'To' field");
    return false;
  }
}
//***  ***//
function validateDate()
{
  var date_year  = $("date_year").value;
  var date_month = $("date_month").value;
      	
  if (date_year != "" && date_month != "")
  {
    return date_month + "-" + date_year;
  }
  else
  {
    alert("You must choose a correct date in the 'Date' field");
    return false;
  }
}

/* ********************* ORDER ************************** */

function initOrder()
{
  order_data   = Array();
  order_fields = Array
		         (
		           Array("Order:               ", "title"),
		           Array("Credit Card          ", "order_id_credit_card"),
		           Array("World Pay ID         ", "order_world_pay_order_code"),
		           Array("AVS Code             ", "order_avs_code"),
		           Array("Check Date           ", "order_check_date"),
		           Array("Tracking Number      ", "order_tracking_number"),
		           Array("Shipping Date        ", "order_shipping_date"),
		           
		           Array("Customer:            ", "title"),
		           Array("Name                 ", "customer_name"),
		           Array("Email                ", "customer_email"),
		           Array("Date of Birth        ", "customer_date_of_birth"),
		           Array("Gender               ", "customer_gender"),
		           Array("Type                 ", "customer_type"),
		           
		           Array("Shipping Address:    ", "title"),
		           Array("Name                 ", "shipping_address_name"),
		           Array("Address              ", "shipping_address_address"),
		           Array("State/Province/Region", "shipping_address_province"),
		           Array("City                 ", "shipping_address_city"),
		           Array("ZipCode / POBOX      ", "shipping_address_zip_code"),
		           Array("Phone                ", "shipping_address_phone"),
		           
		           Array("Billing Address:     ", "title"),
		           Array("Country              ", "billing_address_id_country"),
		           Array("Name                 ", "billing_address_name"),
		           Array("Address              ", "billing_address_address"),
		           Array("State/Province/Region", "billing_address_province"),
		           Array("City                 ", "billing_address_city"),
		           Array("ZipCode / POBOX      ", "billing_address_zip_code"),
		           Array("Phone                ", "billing_address_phone")
		         );
                 
  for (var i = 0; i < order_fields.length; i++)
  {
  	order_data[i] = getFieldValue(order_fields[i][1]);
  }
}

function submitOrder(OS, PS)
{
  $("order_status_code").value   = OS;
  $("payment_status_code").value = PS;
  
  if (confirmSubmitOrder())
  {
    document.forms.order.submit();
  }
}

function confirmSubmitOrder()
{
  var message = Array();
  var count = -1;
  for (var i = 0; i < order_fields.length; i++)
  {
  	if (order_fields[i][1] == "title")
  	{
  	  count++;
  	  message[count] = "";
  	}
  	
  	var value = getFieldValue(order_fields[i][1]);
  	if (value)
  	{
  	  if (order_data[i] != value)
  	  {
  	  	var from = order_data[i] != "" ? "From '" + order_data[i] + "'" : "";
  	  	message[count] += "     " + order_fields[i][0] + ": " + from + " To '" + value + "'\n";
  	  }
  	}
  }
  
  var msg   = "";
  var count = -1;
  for (var i = 0; i < order_fields.length; i++)
  {
  	if (order_fields[i][1] == "title")
  	{
  	  count++;
  	  if (message[count] != "")
  	  {
  	  	msg += "\n" + order_fields[i][0] + "\n\n" + message[count];
  	  }
  	}
  }
  
  if (msg != "")
  {
  	if (!confirm("Are you sure to save the next changes:\n\n" + msg + "\n\n"))
  	{
  	  return false;
  	}
  }
  
  return true;
}

function getFieldValue(field_name)
{
  var field      = $(field_name);
  var field_date = $(field_name + "_year");
  var value;
  if (field)
  {
  	if (field.type == "select-one")
  	{
  	  value = field[field.selectedIndex].text;
  	}
  	else if (field.type == "text")
  	{
  	  value = field.value;
  	}
  	else if (field.type == "textarea")
  	{
  	  value = field.value;
  	}
  }
  else if (field_date)
  {
  	var year  = $(field_name + "_year");
  	var month = $(field_name + "_month");
  	var day   = $(field_name + "_day");
  	
  	value = (
  	          month[month.selectedIndex].text != "" && 
  	          day[day.selectedIndex].text     != "" && 
  	          year[year.selectedIndex].text   != ""
  	        ) 
  	        ? month[month.selectedIndex].text + "-" + day[day.selectedIndex].text + "-" + year[year.selectedIndex].text
  	        : "Empty";
  }
  
  return value;
}

/* ********************* Refund **************** */

function activateRefundDetail(control)
{
  var refund_qty     = $("refund_detail_" + control.value + "_refund_qty"    );
  var devolution_qty = $("refund_detail_" + control.value + "_devolution_qty");
  var amount         = $("refund_detail_" + control.value + "_amount"        );
  
  if (control.checked)
  {
  	refund_qty.readOnly     = false;
  	devolution_qty.readOnly = false;
  	amount.readOnly         = false;
  }
  else
  {
  	refund_qty.value     = "";
  	devolution_qty.value = "";
  	amount.value         = "";
  	
  	refund_qty.readOnly     = true;
  	devolution_qty.readOnly = true;
  	amount.readOnly         = true;
  }
}

function sumCheckRefundDetail(control)
{
  var id = control.id;
  var id = id.replace(/refund_detail_/, "").replace(/_refund_qty/, "");
  
  var price_per_item = parseFloat($("price_per_item_" + id).value);
  
  var amount = $("refund_detail_" + id + "_amount");
  
  var total = parseFloat(control.value) * price_per_item;
  
  amount.value = total ? total.toFixed(2) : "0.00";
}


/* ********************* Resend **************** */

function activateResendDetail(control)
{
  var resend_qty     = $("resend_detail_" + control.value + "_resend_qty");
  
  if (control.checked)
  {
  	resend_qty.readOnly     = false;
  }
  else
  {
  	resend_qty.value     = "";
  	
  	resend_qty.readOnly     = true;
  }
}

/* ********** ************************************** ************* */ 


function checkAll(control, table)
{
  var table = $(table);
  var elements = table.descendants();
  
  for (e in elements)
  {
  	if (elements[e].type == "checkbox")
  	{
  	  var checkbox = $(elements[e]);
  	  if ((control.checked && !checkbox.checked) || (!control.checked && checkbox.checked))
  	  {
  	  	checkbox.click();
  	  }
  	}
  }
}

function go(url)
{
  document.location.href = url;
}

//For all
Ajax.Responders.register(
 {
  onCreate:   function() { Element.show("processing"); },
  onComplete: function() { Element.hide("processing"); }
});	

function getUrlFromName(name)
{
  var search  = Array('Á','É','Í','Ó','Ú','Ñ','á','é','í','ó','ú','ñ');
  var replace = Array('A','E','I','O','U','N','a','e','i','o','u','n');
  
  for (var i=0; i<search.length; i++)
  {
    name = name.replace(search[i], replace[i]);
  }
  
  name = name.toLowerCase().replace(/[\/ \s]/g, '|');
  
  return name;
}


function submitForm(form)
{
  var result = true;
  if (typeof(preSubmitForm) == "function")
  {
  	result = preSubmitForm();
  }
  
  if (result)
  {
    eval("document.forms." + form + ".submit()");
  }
}

/********** AJAX *****************/
function loadStoreProductSelect(url, id)
{
  new Ajax.Updater('offer_store_product_store_product_id', 
                     url, 
                     {asynchronous:true, evalScripts:false, parameters:"store_id="+id});
}



/************** Función para conseguir position fixed en IE6 ****************/

var theTop = 180;

function positionFixedDiv()
{
  window.onscroll = moverDiv;
}

function moverDiv()
{
  if (window.innerHeight)
  {
    pos = window.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop)
  {
    pos = document.documentElement.scrollTop;
  }
  else if (document.body)
  {
    pos = document.body.scrollTop;
  }

  if (pos < theTop)
  {
    pos = theTop;
  }
  else
  {
    pos += 100;
  }

  document.getElementById("processing").style.top = pos + "px";
}

/************** Función para PopUp ****************/


function popUpCenterSameScroll(URL, ancho, alto)
{
  var winl = (screen.width-ancho)/2;
  var wint = (screen.height-alto)/2;
  var settings;
		
  settings ='toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,';
  settings +='height='+alto+',';
  settings +='width='+ancho+',';
  settings +='top='+wint+',';
  settings +='left='+winl;

  eval("window.open(URL, 'KoechCorp', '" + settings + "');");
}

/*** POCH 2009-03-23 ***/
function isEnter(e)
{
  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;
    
  return (key == 13) ? true : false;
}

function seachValueOnSelect(object, e, srcObject, dstObject)
{
  if (isEnter(e))
  {
	var oSrcWindow = document.getElementById(srcObject);
	var oTgtWindow = document.getElementById(dstObject);
	
	clearAll(srcObject);
	
	if (object.length==0)
	{
	  return false;
	}
	else
	{
	  for (i = 0; i < oSrcWindow.options.length; i++) 
      {
      	if (oSrcWindow.options[i].text.toLowerCase() == object.value.toLowerCase()) 
        {
          oSrcWindow.options[i].selected = true;
          moveItemsExtToSelected(srcObject, dstObject);
          clearAll(srcObject);
          object.focus();
          object.select();
          return false;
        }
      }
      clearAll(srcObject);
      object.focus();
      object.select();
	  return false;
	}
	return false;
  }
  
}
  